package com.cordershy.service;

import com.cordershy.mapper.depositMapper;
import com.cordershy.pojo.debt;
import com.cordershy.pojo.deposit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service
public class depositService {
    @Autowired
    depositMapper depositMapper;
    @Transactional
    @Cacheable(value = "accountCache",key = "'allDeposits'")
    public List<deposit> selectAll(String username){
        List<deposit> deposits = depositMapper.selectAll(username);
        Collections.reverse(deposits);
        return deposits;
    }
    @Transactional
    @Cacheable(value = "accountCache",key = "'depositid'+#depositid")
    public deposit selectById(int depositid){
        deposit deposit = depositMapper.select(depositid);
        if (deposit==null){
            return null;
        }
        return deposit;
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @CachePut(value = "accountCache",key = "'depositid'+#deposit.depositid")
    public deposit addDeposit(deposit deposit){
        depositMapper.insert(deposit);
        return  deposit;
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @CachePut(value = "accountCache",key = "'depositid'+#deposit.depositid")
    public deposit updateDeposit(deposit deposit){
        deposit temp = selectById(deposit.getDepositid());
        if (temp!=null){
            depositMapper.update(deposit);
        }else {
            return null;
        }
       return deposit;
    }
    @Transactional(propagation = Propagation.REQUIRED)
    @CacheEvict(value = "accountCache",key = "'depositid'+#depositid")
    public int deleteDeposit(int depositid){
      return   depositMapper.delete(depositid);
    }
}
